package com.oktest.measure.ui.fragment.mine

import android.content.Intent
import android.os.Bundle
import android.view.View
import com.cali.common.kt.jsonBody
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.dialog.alertdialog.helper.CommonDialogHelper
import com.cali.libcore.http.RetrofitManagement
import com.oktest.measure.LoginActivity
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.http.Api
import com.oktest.measure.kt.API_SUCCESS_CODE
import com.oktest.measure.kt.resultTryContext
import kotlinx.android.synthetic.main.download_layout_dialog_default.view.*
import kotlinx.android.synthetic.main.fragment_mine_setting.*
import kotlinx.coroutines.launch

/**
 * @Author hhh
 * @Date 2020/9/17
 */
class MineSettingFragment : BaseFragment() {

    override fun getLayoutId(): Int {
        return R.layout.fragment_mine_setting
    }

    override fun initData(savedInstanceState: Bundle?) {
        toolbarHelper?.apply {
            setTitleText("设置")
        }
        btnExit.setOnClickListener {
            outDialog()
        }
        tvVersion.setOnClickListener {}
    }
    private val dialogHelper by lazy {
        CommonDialogHelper(context!!)
    }

    private fun outDialog() {
        val receivedLayout = View.inflate(context, R.layout.download_layout_dialog_default, null)
        receivedLayout?.apply {
            dialogContent.text = "确定退出吗？"
            dialogTitle.text = "温馨提示"
            btnCancel.setOnClickListener {
                dialogHelper.dismiss()
            }
            btnOk.setOnClickListener {
                dialogHelper.dismiss()
                loginOut()
            }
        }
        dialogHelper.show(receivedLayout, false, isMath = false)
    }

    private fun loginOut() = launch {
        val outResult = resultTryContext {
            val map = hashMapOf<String, Any>()
            map["mobile"] = MyApp.personInfo.mobile
            map["code"] = ""
            RetrofitManagement.instance.getService(Api::class.java).logout(map.jsonBody())
                .execute().body()
        }
        if (outResult.code == API_SUCCESS_CODE) {
            startActivity(Intent(context, LoginActivity::class.java))
            MyApp.resetInfo()
            activity?.finish()
        } else {
            error(outResult)
        }
    }

    override fun hasBackIcon(): Boolean {
        return true
    }

    override fun hasToolbar(): Boolean {
        return true
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }
}